#!/bin/bash

# Docker编译脚本 for Go 1.23.0+
# 使用方法: ./docker-build.sh [编译参数]

set -e

# 镜像名称和标签
GO_IMAGE="golang:1.23.0"
CONTAINER_NAME="go_build_$(date +%s)"

# 项目根目录（假设脚本在项目根目录运行）
PROJECT_ROOT=$(pwd)
PROJECT_NAME="mig2kwdb"

echo "开始使用Go 1.23.0编译项目..."

# 检查Docker是否可用
if ! command -v docker &> /dev/null; then
    echo "错误: 未找到Docker，请先安装Docker"
    exit 1
fi

# 拉取Go 1.23.0镜像
echo "拉取Go 1.23.0 Docker镜像..."
docker pull $GO_IMAGE

# 创建构建目录
mkdir -p build
GO_CACHE_DIR="$HOME/.go-docker-cache"
mkdir -p "$GO_CACHE_DIR"

# 构建编译命令
BUILD_CMD="CGO_ENABLED=0 go build -ldflags '-s -w' -o build/$PROJECT_NAME"

# 如果有额外参数，添加到编译命令
if [ $# -gt 0 ]; then
    BUILD_CMD="$BUILD_CMD $@"
fi

echo "编译命令: $BUILD_CMD"

# 运行Docker容器进行编译
echo "开始编译..."
docker run --rm \
    -v "$PROJECT_ROOT:/workspace" \
    -w /workspace \
    --name "$CONTAINER_NAME" \
    -v "$GO_CACHE_DIR:/go/pkg/mod" \
    -e GOPROXY=https://goproxy.cn,direct \
    $GO_IMAGE \
    sh -c "
        echo 'Go版本:'
        go version
        echo '开始编译项目...'
        $BUILD_CMD
    "

# 检查编译结果
if [ -f "build/$PROJECT_NAME" ]; then
    \cp "build/$PROJECT_NAME"  "./$PROJECT_NAME"
    echo "✅ 编译成功！"
    echo "📁 输出文件: build/$PROJECT_NAME"
    # 显示文件信息
    ls -lh "build/$PROJECT_NAME"
else
    echo "❌ 编译失败，未找到输出文件"
    echo "当前目录内容:"
    ls -la
    echo "build目录内容:"
    ls -la build/ 2>/dev/null || echo "build目录不存在"
    exit 1
fi
